package com.qf.smsplatform.interfaces.service.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.enums.InterfaceExceptionEnums;
import com.qf.smsplatform.common.index.StandardSubmit;
import com.qf.smsplatform.interfaces.exception.SmsException;
import com.qf.smsplatform.interfaces.form.SmsInterfaceForm;
import com.qf.smsplatform.interfaces.stream.PreSendOutputStream;
import com.qf.smsplatform.interfaces.service.SmsInterfaceService;
import com.qf.smsplatform.interfaces.service.api.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class SmsInterfaceServiceImpl implements SmsInterfaceService {

    private  final  int HTTP = 1;

//    @Value("${mobileRegex}")
//    private String mobileRegex;


    @Resource
    private CacheService cacheService;
//
//    @Autowired
//    private ObjectMapper objectMapper;

    @Resource
    private PreSendOutputStream preSendOutputStream;

    @Override
    public void checkParameters(SmsInterfaceForm smsInterfaceForm) {
        //code：101 校验clientID ---- 通过调用缓存模块校验
        String clientID = smsInterfaceForm.getClientID();
        Map map = cacheService.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + clientID);
        if (map == null || map.size() == 0) {
            log.info("【接口模块】认证错误：clientId错误   clientID = {}" ,clientID);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_CLIENTID_ERROR);
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        //code：102 校验pwd ---- 通过101中查询的信息equals比较
        String userPwd = smsInterfaceForm.getPwd();
        if (StringUtils.isEmpty(userPwd) || !DigestUtils.md5Hex(userPwd).equalsIgnoreCase((String) map.get("pwd"))) {
            // pwd为null，pwd不正确
            log.info("【接口模块】错误。  pwd = {}" , smsInterfaceForm.getPwd());
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_CLIENTID_ERROR);
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        //code：103 校验ip ---- 通过101中查询的信息equals比较
        String ips = (String) map.get("ipaddress");
        String[] ipArray = ips.split(",");
        String userIp = smsInterfaceForm.getIp();
        boolean flag = false;
        for (String ip : ipArray) {
            if (!StringUtils.isEmpty(userIp) && userIp.equalsIgnoreCase(ip)) {
                // ip为null，ip和正确不对应
                flag = true;
                break;
            }
        }
        if (!flag) {
            log.info("【接口模块】IP校验错误  ip = {}" , smsInterfaceForm.getIp());
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_IP_ADDRESS_ERROR);
        }

        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        // 104 校验短信长度 ---- 非空,长度小于500
        String content = smsInterfaceForm.getContent();
        if (StringUtils.isEmpty(content) || content.length() > 500) {
            log.info("【接口模块校验】 消息长度错，为空或超长（目前定为500个字） content = {}", content);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_MESSAGE_CONTENT_ERROR);
        }

        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        // TODO code：105 校验手机号码 ---- 校验手机号格式和手机的号数量 , 有错误手机号 , 不影响执行,将错误手机号,返回给客户端即可.

        //105.1校验手机号不为空或者空串
        String mobile = smsInterfaceForm.getMobile();
        if (StringUtils.isEmpty(mobile)) {
            log.info("【接口模块校验】 手机号错误 mobile = {}", mobile);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR);
        }
        //2.手机号使用分隔符进行分割--分割后长度大于0
        String[] mobileArray = mobile.split(",");
        if (mobileArray.length == 0 || mobileArray.length > 100) {
            log.info("【接口模块校验】 手机号错误 mobile = {}", mobile);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR);
        }
        //3遍历数组
        Set<String> errorMobile = new HashSet<>();
        Set<String> okMoblie = new HashSet<>();
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))[0-9]{8}$";
        for (String s : mobileArray) {
            //封装正确的手机号（发送消息到Rabbitmq）和错误的号码（给客户端）
            if (s.matches(regex)) {
                //手机号正确
                okMoblie.add(s);
            } else {
                //手机号错误
                errorMobile.add(s);
            }
        }
        //判断手机号有没有正确的
        if (okMoblie.size() <= 0) {
            log.info("【接口模块校验】 手机号错误 mobile = {}", mobile);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR);
        }

        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        // TODO code：106 校验srcID ---- 必须是数字
        // 判断
        String srcIDString = smsInterfaceForm.getSrcID();
        long srcID = 0;
        if(srcIDString != null) {
            try {
                srcID =   Long.parseLong(srcIDString);
            } catch (NumberFormatException e) {
                log.info("【接口模块校验】下行编号（srcID）错误 srcId = {}", srcID);
                throw new SmsException(InterfaceExceptionEnums.INTERFACE_SRCID_ERROR);
            }


        }

        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        // 如果全部校验通过,发送消息到MQ,
        // RabbitMQConstants.TOPIC_UPDATE_SMS_REPORT;
        // StandardSubmit submit = new StandardSubmit();

        //1.遍历okMobile，封装submit
        for (String s : okMoblie) {
            StandardSubmit submit = new StandardSubmit();
            submit.setClientID(Integer.valueOf(clientID));
            submit.setSrcSequenceId(srcID);
            submit.setDestMobile(s);
            submit.setMessageContent(content);
            submit.setSource(HTTP);
            preSendOutputStream.output().send(MessageBuilder.withPayload(submit).build());
        }



        //发送消息成功后，将错误手机号响应给客户端
        if (errorMobile.size()>0){
            log.info("【接口模块校验】手机号有错误 errorMobile = {}", errorMobile);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_MOBILE,errorMobile);
        }
    }
}